package com.shuoyue.ycgk.ui.questionbank.practice.freedom;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.entity.FreedomGroup;
import com.shuoyue.ycgk.entity.Option;
import com.shuoyue.ycgk.entity.QuestionParent;
import com.shuoyue.ycgk.entity.QuestionSimple;
import com.shuoyue.ycgk.ui.questionbank.BaseCountActivity;
import com.shuoyue.ycgk.ui.questionbank.CountInfoBean;
import com.shuoyue.ycgk.ui.questionbank.practice.checkall.CheckQuestionAllActivity;
import com.shuoyue.ycgk.ui.questionbank.practice.checkwrongs.CheckQuestionWrongActivity;
import com.shuoyue.ycgk.ui.questionbank.practice.specialtraining.QuestionSpecialInfoAdapter;
import com.shuoyue.ycgk.utils.SizeUtil;
import com.shuoyue.ycgk.utils.SpacesItemDecoration;
import com.shuoyue.ycgk.utils.TimeFomatUtil;
import com.shuoyue.ycgk.views.dialog.common.HintConfirmDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class FreedomCountActivity extends BaseCountActivity {
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;

    public static void start(Context source,
                             String name,
                             int testId,
                             ArrayList<FreedomGroup> questionParents) {
        source.startActivity(new Intent(source, FreedomCountActivity.class)
                .putExtra("name", name)
                .putExtra("testId", testId)
                .putExtra("questions", questionParents)
        );
    }

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.right_num)
    TextView rightNum;
    @BindView(R.id.total_num)
    TextView totalNum;
    @BindView(R.id.right_rate)
    TextView rightRate;
    @BindView(R.id.use_time)
    TextView useTime;
    @BindView(R.id.wrongs)
    Button wrongs;
    @BindView(R.id.answerCard)
    RecyclerView answerCard;
    @BindView(R.id.answerInfo)
    RecyclerView answerInfo;

    ArrayList<FreedomGroup> freedomGroups;
    ArrayList<QuestionParent> questionParents;

    String pagerName;
    QuestionSpecialInfoAdapter questionSpecialInfoAdapter;
    FreedomCountAdapter freedomCountAdapter;
//    UploadAnswerContract.Presenter anserPresenter;

    int testId;

    boolean isUpload = false;

    /**
     * 初始化layouy
     */
    @Override
    protected int getLayoutId() {
        return R.layout.activity_question_freedom_count;
    }

    /**
     * 初始化布局
     */
    @Override
    protected void initView() {
        answerCard.setLayoutManager(new LinearLayoutManager(mContext));
        answerCard.addItemDecoration(new SpacesItemDecoration(SizeUtil.dip2px(mContext, 16), false));
        answerInfo.setLayoutManager(new LinearLayoutManager(mContext));
        answerInfo.addItemDecoration(new SpacesItemDecoration(SizeUtil.dip2px(mContext, 16), false));
    }

    @Override
    public void initData() {
        super.initData();

//        anserPresenter = new UploadAnswerContract.Presenter();
//        anserPresenter.attachView(this);
        pagerName = getIntent().getStringExtra("name");
        testId = getIntent().getIntExtra("testId", -1);
        freedomGroups = (ArrayList<FreedomGroup>) getIntent().getSerializableExtra("questions");
        title.setText(pagerName);

        questionParents = new ArrayList<>();
        for (FreedomGroup groups : freedomGroups) {
            questionParents.addAll(groups.getQuestionDTOS());
        }


        freedomCountAdapter = new FreedomCountAdapter(freedomGroups, (adapter, view, position) -> {
            QuestionSimple questionSimple = (QuestionSimple) adapter.getItem(position);
            CheckQuestionAllActivity.start(mContext, pagerName, questionParents, questionSimple);
        });
        answerCard.setAdapter(freedomCountAdapter);
        setRightRate();
        setTypeUI();
        scrollView.scrollTo(0, 0);

    }

    void setRightRate() {
        CountInfoBean countInfo = count(questionParents);
        rightNum.setText(countInfo.getRightQuestion() + "");
        totalNum.setText(countInfo.getTotalQuestion() + "");
        rightRate.setText("正确率:"
                + (int) (((Float.valueOf(countInfo.getRightQuestion()) / Float.valueOf(countInfo.getTotalQuestion()))) * 100)
                + "%");
        useTime.setText("用时" + TimeFomatUtil.formatmmss((long) (countInfo.getTimeMul() / 1000)));
    }

    void setTypeUI() {
        List<CountInfoBean> countInfos = new ArrayList<>();
        for (FreedomGroup freedomGroup : freedomGroups) {
            CountInfoBean countInfo = count(freedomGroup.getQuestionDTOS());
            countInfo.setTypeStr(freedomGroup.getDetailName());
            countInfos.add(countInfo);

        }
        questionSpecialInfoAdapter = new QuestionSpecialInfoAdapter(countInfos);
        answerInfo.setAdapter(questionSpecialInfoAdapter);
    }


    @Override
    public void finish() {
        HintConfirmDialog hintConfirmDialog = new HintConfirmDialog(mContext, "退出", "是否确认退出");
        hintConfirmDialog.setOkListener(v -> {
//            anserPresenter.uploadAnswer(QuestionUtil.getUserAnswerPager(questionParents, testId), 5, true);
            super.finish();
            hintConfirmDialog.dismiss();
        });
        hintConfirmDialog.show();
    }

    /**
     * 统计
     * 1:正确个数
     * 2:总提数
     * 3.计算正确率
     * 4计算用时
     * 5:是否有错题
     * 6.分类正确率
     */
    CountInfoBean count(List<QuestionParent> questionParents) {
        //
        CountInfoBean countInfo = new CountInfoBean();
        for (QuestionParent questionParent : questionParents) {
            //
            if (questionParent.getIsMaterial() == 1) {
                //材料题
                for (QuestionSimple questionSimple : questionParent.getQuestionSimpleDTOS()) {
                    handleQuestionSimple(questionSimple, countInfo);
                }
            } else {
                handleQuestionSimple(questionParent.getQuestionSimpleDTOS().get(0), countInfo);
            }
        }
        return countInfo;
    }

    void handleQuestionSimple(QuestionSimple questionSimple, CountInfoBean countInfo) {
        //标记为查看答案
        questionSimple.setShowRight(true


        );
        //1.标记是否答对
        if (questionSimple.getMyChooseAnswer() != null &&
                questionSimple.getMyChooseAnswer().size() > 0) {
            //有作答
            StringBuilder sbMine = new StringBuilder();
            for (String o : questionSimple.getMyChooseAnswer()) {
                sbMine.append(o);
            }
            StringBuilder sbRight = new StringBuilder();
            for (Option o : questionSimple.getQuestionSimpleOptionDTOS()) {
                if (o.isRight()) sbRight.append(o.getNo());
            }
            //答对提数+1
            countInfo.setRightQuestion(countInfo.getRightQuestion()
                    + (sbRight.toString().equals(sbMine.toString()) ? 1 : 0));
            //标记是否正确
            questionSimple.setIsAnswerRight(sbRight.toString().equals(sbMine.toString()) ? 1 : 0);
            //增加答题时间(毫秒)
            countInfo.setTimeMul(countInfo.getTimeMul() + questionSimple.getUseTime());
        } else {
            questionSimple.setIsAnswerRight(2);
        }

        //2.总提数加1
        countInfo.setTotalQuestion(countInfo.getTotalQuestion() + 1);
        //
    }

    @OnClick({R.id.back, R.id.wrongs, R.id.rights})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.wrongs:
                CheckQuestionWrongActivity.start(mContext, pagerName, getQuestiongWrongs(questionParents));
                break;
            case R.id.rights:
                CheckQuestionAllActivity.start(mContext, pagerName, questionParents);
                break;

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
